﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

using OptusMobile.Web.ServerComponents.BAL.CustomerManagement;
using OptusMobile.Web.ServerComponents.DAL;
using System.Globalization;
using OptusMobile.Web.ServerComponents.BAL.RecommenderManagement;
using OptusMobile.Web.ServerComponents.BAL.PlanManagement;
using OptusMobile.Web.ServerComponents.BAL.HandsetManagement;

namespace OptusMobile.Web.CustomerPortal
{
    public partial class CustomerHome : System.Web.UI.Page
    {
        string userName = string.Empty;
        CustomerManager customerManager = new CustomerManager();
        CustomerContract currentCustomer = new CustomerContract();
        List<CustomerUsageHistroy> historyRecords = new List<CustomerUsageHistroy>();
        RecommenderManager recommenderManager = new RecommenderManager();
        CustomerUsageHistroy historyAverage = new CustomerUsageHistroy();
        PlanManager planManager = new PlanManager();
        HandsetManager handsetManager = new HandsetManager();

        protected void Page_PreRender(object sender, EventArgs e)
        {

            Authenticate();

            this.userName = Session["ID"].ToString();
            currentCustomer = customerManager.GetCustomerContractInformation(this.userName);
            historyRecords = customerManager.GetCustomerUseHistory(this.currentCustomer.contractID);
            DisplayCustomerInfo();
            DisplayRecommendedHandsets();
            DisplayRecommendedPlan();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string cssPath = "../css/Customer.css";
            HtmlLink link = new HtmlLink();
            link.Href = cssPath;
            link.Attributes["rel"] = "stylesheet";
            link.Attributes["type"] = "text/css";
            PlaceHolder1.Controls.Add(link);
        }

        private void Authenticate()
        {
            if (Session["ID"] == null || Session["flag"] == null)
            {
                Response.Redirect("../NotLoginError.aspx");
            }
            else
            {
                string flag = Session["flag"].ToString();
                if (flag.Equals("user"))
                {
                    string loginname = Session["ID"].ToString();
                    //this.lblogin.Text = loginname;
                }
                else
                {
                    Response.Redirect("../NotLoginError.aspx");
                }
            }
        }

        private void DisplayRecommendedPlan()
        {
            if (this.historyRecords.Count > 0)
            {
                HandsetContract newContract = recommenderManager.RecommendPlan(this.historyRecords, this.currentCustomer.HandsetContract);
                decimal currentActualFee = Convert.ToDecimal(this.LabelAveActualFee.Text.Remove(this.LabelAveActualFee.Text.IndexOf('$'),1));
                decimal newActualFee = planManager.CalculateActualValue(newContract.Cap.Plans, this.historyAverage, newContract.ExtraMessage, newContract.ExtraData);

                string optionTextPrex = "LabelOptionText";
                string optionNamePrex = "LabelOptionName";
                int currentIndex = 1;

                string planUdgradeValue = string.Empty;
                string messageUpgradeValue = string.Empty;
                string dataUpgradeValue = string.Empty;

                if (newContract.Cap.Plans != this.currentCustomer.HandsetContract.Cap.Plans)
                {
                    string labeOptionTextID = optionTextPrex + (currentIndex).ToString();
                    string labeOptionNameID = optionNamePrex + (currentIndex).ToString();
                    Label labeOptionText = this.PlaceHolder1.FindControl(labeOptionTextID) as Label;
                    Label labeOptionName = this.PlaceHolder1.FindControl(labeOptionNameID) as Label;
                    currentIndex++;

                    if (labeOptionText != null)
                    {
                        labeOptionText.Text = "New Plan";
                    }
                    if (labeOptionName != null)
                    {
                        labeOptionName.Text = newContract.Cap.Plans.planName;
                    }

                    if (newContract.Cap.Plans.monthlyFee == 99)
                    {
                        planUdgradeValue = "Unlimited call & message,";
                    }
                    else
                    {
                        decimal bonusValue = newContract.Cap.Plans.totalValue - this.currentCustomer.HandsetContract.Cap.Plans.totalValue;
                        planUdgradeValue = bonusValue.ToString("F02") + "$ more call & message value, ";
                    }
                }
                if (newContract.ExtraMessage.exMessagePrice!=0 && (newContract.ExtraMessage != this.currentCustomer.HandsetContract.ExtraMessage))
                {
                    string labeOptionTextID = optionTextPrex + (currentIndex).ToString();
                    string labeOptionNameID = optionNamePrex + (currentIndex).ToString();
                    Label labeOptionText = this.PlaceHolder1.FindControl(labeOptionTextID) as Label;
                    Label labeOptionName = this.PlaceHolder1.FindControl(labeOptionNameID) as Label;
                    currentIndex++;

                    if (labeOptionText != null)
                    {
                        labeOptionText.Text = "New SMS Package";
                    }
                    if (labeOptionName != null)
                    {
                        labeOptionName.Text = newContract.ExtraMessage.exMessagePackageName;
                    }

                    if (newContract.ExtraMessage.exMessagePrice==5)
                    {
                        messageUpgradeValue = "Unlimited message to Optus,";
                    }
                    else if(newContract.ExtraMessage.exMessagePrice==10)
                    {
                        messageUpgradeValue = "500 free message to anyone,";
                    }
                    else if (newContract.ExtraMessage.exMessagePrice == 15)
                    {
                        messageUpgradeValue = "Unlimited message to anyone,";
                    }
                    else
                    {

                    }
                }
                if (newContract.ExtraData.exDataPrice != 0 && (newContract.ExtraData != this.currentCustomer.HandsetContract.ExtraData))
                {
                    string labeOptionTextID = optionTextPrex + (currentIndex).ToString();
                    string labeOptionNameID = optionNamePrex + (currentIndex).ToString();
                    Label labeOptionText = this.PlaceHolder1.FindControl(labeOptionTextID) as Label;
                    Label labeOptionName = this.PlaceHolder1.FindControl(labeOptionNameID) as Label;
                    currentIndex++;

                    if (labeOptionText != null)
                    {
                        labeOptionText.Text = "New data package";
                    }
                    if (labeOptionName != null)
                    {
                        labeOptionName.Text = newContract.ExtraData.exDataPackage;
                    }

                    decimal bonusValue = newContract.ExtraData.exDataAmount - this.currentCustomer.HandsetContract.ExtraData.exDataAmount;
                    dataUpgradeValue = bonusValue.ToString("F03") + "MB more data ";
                }

                if (currentIndex > 1)
                {
                    string labeOptionTextID = optionTextPrex + (currentIndex).ToString();
                    string labeOptionNameID = optionNamePrex + (currentIndex).ToString();
                    Label labeOptionText = this.PlaceHolder1.FindControl(labeOptionTextID) as Label;
                    Label labeOptionName = this.PlaceHolder1.FindControl(labeOptionNameID) as Label;
                    currentIndex++;

                    if (labeOptionText != null)
                    {
                        labeOptionText.Text = "New monthly cost";
                    }
                    if (labeOptionName != null)
                    {
                        labeOptionName.Text = newActualFee.ToString("F02");
                    }

                    decimal savedFee = currentActualFee - newActualFee;
                    this.LabelUpgradeValue.Text = "You get " + planUdgradeValue + messageUpgradeValue + dataUpgradeValue + " and ";
                    this.LabelSaveValue.Text = "save " + savedFee.ToString("F02") + " dollars every month!";
                }
                else
                {
                    this.LabelUpgradeValue.Text = string.Empty;
                    this.LabelSaveValue.Text = "Your current plan is already the best one!";
                }
            }
            else
            {
                this.LabelSaveValue.Text = "No sufficient usage history for plan recommendation";
            }
        }

        private void DisplayCustomerInfo()
        {
            if (this.currentCustomer == null)
            {

            }
            else
            {
                DisplayContractSummary();
                DisplayUsageHistory();
                DisplayAverageUse();
                DisplayPersonalInfo();
            }
        }

        private void DisplayContractSummary()
        {
            //displays date short format
            String dateFormat = "d";

            this.LabelContractState.Text = this.currentCustomer.ContractState.stateName;
            this.LabelEndDate.Text = this.currentCustomer.endDate.ToString(dateFormat, DateTimeFormatInfo.InvariantInfo);
            if (this.currentCustomer.HandsetContract.ExtraData.exDataPrice != 0)
            {
                this.LabelExtraData.Text = this.currentCustomer.HandsetContract.ExtraData.exDataPackage;
            }
            else
            {
                this.LabelExtraData.Text = "No Data Package";
            }
            if (this.currentCustomer.HandsetContract.ExtraMessage.exMessagePrice != 0)
            {
                this.LabelExtraMessage.Text = this.currentCustomer.HandsetContract.ExtraMessage.exMessagePackageName;
            }
            else
            {
                this.LabelExtraMessage.Text = "No Message package";
            }
            this.LabelHandset.Text = this.currentCustomer.HandsetContract.Cap.HandsetBasicInformation.handsetModole;
            this.LabelMobileNumber.Text = this.currentCustomer.HandsetContract.cellphoneNumber;
            this.LabelPlanName.Text = this.currentCustomer.HandsetContract.Cap.Plans.planName;
            this.LabelStartDate.Text = this.currentCustomer.startDate.Date.ToString(dateFormat, DateTimeFormatInfo.InvariantInfo);
        }

        private void DisplayPersonalInfo()
        {
            this.LabelName.Text = this.currentCustomer.Customer.customerName;
            this.LabelOccupation.Text = this.currentCustomer.Customer.Occupation.occupationName;
            if (this.currentCustomer.Customer.customerGender == "M")
            {
                this.LabelGender.Text = "Male";
            }
            else
            {
                this.LabelGender.Text = "Female";
            }
            this.LabelAge.Text = this.currentCustomer.Customer.customerAge.ToString();
            this.LabelEmail.Text = this.currentCustomer.Customer.customerEmail;
        }

        private void DisplayUsageHistory()
        {
            if (this.historyRecords.Count > 0)
            {
                this.ListViewHistory.DataSource = this.historyRecords;
                this.ListViewHistory.DataBind();
            }
        }

        private void DisplayRecommendedHandsets()
        {
            string labelPrex = "LabelRecHandset";
            string imagePrex = "Image";
            List<V_HandsetBasicInformation> recommendedHandsets =
                recommenderManager.RecommendHandsetsUsingAllRatings(currentCustomer.Customer.customerID,this.userName);
            int handsetNumber = recommendedHandsets.Count;
            for(int i =0; i<handsetNumber;i++)
            {
                V_HandsetBasicInformation handset = recommendedHandsets[i];
                string labelID = labelPrex + (i+1).ToString();
                string imageID = imagePrex + (i+1).ToString();
                Label label = this.PlaceHolder1.FindControl(labelID) as Label;
                ImageButton image = this.PlaceHolder1.FindControl(imageID) as ImageButton;

                if (label != null)
                {
                    label.Text = handset.handsetModole;
                }
                if (image != null)
                {
                    image.Visible = true;
                    V_HandsetImage vimage = handsetManager.GetHandsetImage(handset.handsetID);
                    string imageURL = ".." + vimage.imagePath + vimage.imageName;
                    image.ImageUrl = imageURL;
                    image.AlternateText = handset.handsetID;
                }
            }
        }

        private void CalculateAverageUse()
        {
            List<CustomerUsageHistroy> lastSixMonthesUsedHistoryRecords =
                this.historyRecords.OrderByDescending(o => o.buildDate).Take(6).ToList();

            this.historyAverage.callsToOptus = (int)lastSixMonthesUsedHistoryRecords.Average(h => h.callsToOptus);
            this.historyAverage.callsToOther = (int)lastSixMonthesUsedHistoryRecords.Average(h => h.callsToOther);
            this.historyAverage.data = lastSixMonthesUsedHistoryRecords.Average(h => h.data);
            this.historyAverage.messageToOptus = (int)lastSixMonthesUsedHistoryRecords.Average(h => h.messageToOptus);
            this.historyAverage.messageToOther = (int)lastSixMonthesUsedHistoryRecords.Average(h => h.messageToOther);
            this.historyAverage.totalCallTimeToOptus = (int)lastSixMonthesUsedHistoryRecords.Average(h => h.totalCallTimeToOptus);
            this.historyAverage.totalCallTimeToOther = (int)lastSixMonthesUsedHistoryRecords.Average(h => h.totalCallTimeToOther);
        }

        private void DisplayAverageUse()
        {
            if (this.historyRecords.Count > 0)
            {
                CalculateAverageUse();

                this.LabelAveCallsToOptus.Text = this.historyAverage.callsToOptus.ToString();
                this.LabelAveCallsToOther.Text = this.historyAverage.callsToOther.ToString();
                this.LabelAveData.Text = this.historyAverage.data.ToString("F03")+"MB";
                this.LabelAveMessageToOptus.Text = this.historyAverage.messageToOptus.ToString();
                this.LabelAveMessageToOther.Text = this.historyAverage.messageToOther.ToString();
                this.LabelAveCallTimeToOptus.Text = this.historyAverage.totalCallTimeToOptus.ToString("F00")+"Mins";
                this.LabelAveCallTimeToOther.Text = this.historyAverage.totalCallTimeToOther.ToString("F00") + "Mins";

                OptusMobile.Web.ServerComponents.DAL.Plan currentPlan = this.currentCustomer.HandsetContract.Cap.Plans;
                decimal? callToOptusValue = (currentPlan.flagCall * this.historyAverage.callsToOptus + currentPlan.callRate * (decimal)this.historyAverage.totalCallTimeToOptus) / 100;
                decimal? callToOtherValue = (currentPlan.flagCall * this.historyAverage.callsToOther + currentPlan.callRate * (decimal)this.historyAverage.totalCallTimeToOther) / 100;

                decimal? totalCallValue = callToOptusValue + callToOtherValue;
                decimal messageToOptusValue = currentPlan.perMessageFee * this.historyAverage.messageToOptus / 100;
                decimal messageToOtherValue = currentPlan.perMessageFee * this.historyAverage.messageToOther / 100;
                decimal totalMessageValue = messageToOptusValue + messageToOtherValue;
                decimal dataValue = (decimal)(this.historyAverage.data * 0.015 * 1024);
                decimal totalValue = totalCallValue.Value + totalMessageValue + dataValue;

                this.LabelAveTotalCallValue.Text = totalCallValue.Value.ToString("F02")+"$";
                this.LabelAveTotalMessageValue.Text = totalMessageValue.ToString("F02") + "$";
                this.LabelAveDataValue.Text = dataValue.ToString("F02") + "$";
                this.LabelAveTotalValue.Text = totalValue.ToString("F02") + "$";

                #region calculates the actual average monthly fee

                decimal actualValue = currentPlan.monthlyFee;
                ExtraData dataPackage = this.currentCustomer.HandsetContract.ExtraData;
                ExtraMessage messagePackage = this.currentCustomer.HandsetContract.ExtraMessage;

                //calculates calls and messages value
                actualValue = planManager.CalculateActualValue(currentPlan, this.historyAverage, messagePackage, dataPackage);

                this.LabelAveActualFee.Text = actualValue.ToString("F02") + "$";
                #endregion
            }
        }

        protected void ImageButton_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton button = sender as ImageButton;
            if (button != null)
            {
                string handsetID = button.AlternateText;
                Response.Redirect("../Handset/ShowHandsetDetail.aspx?handsetID=" + handsetID);
            }
        }

    }

}
